﻿#include <iostream>
#include <json/json.h>
#include <json/value.h>
#include <json/reader.h>
#include <boost/asio.hpp>
#include <memory>
#define MAX_LENGTH 1024
#define HEAD_ID_LEN 2
#define HEAD_MSG_LEN 2
using namespace std;
using boost::asio::ip::tcp;
int main()
{
	boost::asio::io_context ioc;
	const string server_ip = "127.0.0.1";
	unsigned short  port = 3333;
	tcp::endpoint ep(boost::asio::ip::make_address(server_ip), port);
	boost::system::error_code ec;
	tcp::socket sock(ioc);
	sock.connect(ep,ec);
	if (ec) {
		cout << "连接服务器失败" << endl;
	}
	char buf[MAX_LENGTH] = { 0 };
	while (true) {
		unsigned short msg_id = 1001;
		Json::Value send_json;
		send_json["data"] = "hello world!!";
		send_json["id"] = 1001;
		string string_json =  send_json.toStyledString();
		//发送数据id
		msg_id = boost::asio::detail::socket_ops::host_to_network_short(msg_id);
		sock.send(boost::asio::buffer(&msg_id, HEAD_ID_LEN));
		//发送数据大小
		unsigned short send_head = string_json.size();
		send_head = boost::asio::detail::socket_ops::host_to_network_short(send_head);
		sock.send(boost::asio::buffer(&send_head, HEAD_MSG_LEN));
		sock.send(boost::asio::buffer(string_json.c_str(), string_json.size()));
		memset(buf, 0, MAX_LENGTH);
		//接收id
		sock.receive(boost::asio::buffer(buf, HEAD_ID_LEN));
		msg_id = boost::asio::detail::socket_ops::network_to_host_short(*((unsigned short*)buf));
		memset(buf, 0, MAX_LENGTH);
		//接收大小
		sock.receive(boost::asio::buffer(buf, HEAD_MSG_LEN));
		short head_size;
		head_size = boost::asio::detail::socket_ops::network_to_host_short(*((unsigned short*)buf));
		memset(buf, 0, MAX_LENGTH);
		sock.receive(boost::asio::buffer(buf, head_size));
		string recv_str(buf, head_size);
		Json::Reader reader;
		reader.parse(recv_str, send_json);
		cout <<"消息id is"<< msg_id<< " 服务器回复：" << send_json.toStyledString() << std::endl;
		getchar();	
	}

	return 0;
}